package com.cdtu.sys.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.cdtu.sys.domain.User;
import com.cdtu.sys.domain.UserVo;
import com.cdtu.sys.service.ILogInfoService;
import com.cdtu.sys.service.IUserService;
import com.cdtu.sys.utils.SysConstant;
import com.cdtu.sys.utils.WebUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Resource
    private IUserService userService;
    @Autowired
    private ILogInfoService logInfoService;
    /**
     * 进入登录页面
     */
    @GetMapping("/toLogin")
    public String toLogin(){
        return "system/main/login";
    }

    /**
     * 创建验证码
     */
    @GetMapping("/getCode")
    public void getCode(HttpServletResponse httpServletResponse) throws IOException {
        //创建验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116, 36, 4, 5);
        //获取验证码，并出入Session域
        String code = lineCaptcha.getCode();
        WebUtils.getHttpSession().setAttribute("code",code);
        //将图片响应给前端
        ImageIO.write(lineCaptcha.getImage(),"JPEG",WebUtils.getHttpServletResponse().getOutputStream());
    }

    @PostMapping("/login")
    public String login(UserVo userVo, HttpServletRequest request){
        String sessionCode = (String) WebUtils.getHttpSession().getAttribute("code");
        //session中没有值，用户没有先获取session
        if (sessionCode == null) {
            WebUtils.getHttpServletRequest().setAttribute("error", SysConstant.USER_LOGIN_CODE_ERROR_MSG);
            return "system/main/login";
        }
        //验证码不相等，输入验证码错误
        if (!sessionCode.equalsIgnoreCase(userVo.getCode())) {
            WebUtils.getHttpServletRequest().setAttribute("error",SysConstant.USER_LOGIN_CODE_ERROR_MSG);
            return "system/main/login";
        }

        //验证码正确，开始判断用户名、密码是否正确
        //查询用户信息。
        User user = userService.login(userVo);
        if (user == null) {         //用户信息不存在，用户名或密码错误
            WebUtils.getHttpServletRequest().setAttribute("error",SysConstant.USER_LOGIN_ERROR_MSG);
            return "system/main/login";
        }
        //用户名、密码正确，将用户信息存入session中。
        WebUtils.getHttpSession().setAttribute("user",user);
        logInfoService.addLogInfo(user,request);//保存登录日志
        return "system/main/index";
    }

}
